<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/phorm/database/core/Database.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/phorm/database/core/IDatabaseRecord.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/phorm/utils/FileUtils.php';

require 'DatabaseRecord.php';
class CouchDBRecord extends DatabaseRecord implements IDatabaseRecord
{
	const kTypeKey = 'type';
	
	public $id  = null;
	public $rev = null;
	
	public function initWithColumns() { /* pass */ }
	public function create() { /* pass */ }
	public function emptyThis() { /* pass */ }	
	public function drop() { /* pass */ }
	
	public function initWithArray($array)
	{
		$keys = array_keys($array);
		
		foreach($keys as $property)
		{
			
			if($property != CouchDBRecord::kTypeKey)
			{
				if($property == '_id' || $property == '_rev')
				{
					$key = substr($property, 1);
					$this->{$key} = $array[$property];
				}
				else
				{
					if(isset($this->columns[$property]))
					{
						$this->columns[$property]->value = $array[$property];
					}
				}
			}
		}
		
		$this->isNew = false;
	}
	
	public function initWithPrimaryKey($id)
	{
		$dbh       =& Database::connection();
		try
		{
			$document  = $dbh->document($id);
			$this->initWithArray($document);
		}
		catch(Exception $e)
		{
			// pass;
		}
	}
	
	public function save()
	{
		$temp  = array();
		$files = array();
		
		foreach($this->columns as $key=>$object)
		{
			$temp[$key] = $object->value;
		}
		
		$temp[CouchDBRecord::kTypeKey] = strtolower(get_class($this));
		
		$dbh       =& Database::connection();
		
		if(empty($this->id))
		{
			$json      = json_encode($temp);
			$result    = $dbh->put($json);
			$this->id  = $result['id'];
		}
		else
		{
			if(!empty($this->rev))
			{
				$temp['_id']  = $this->id;
				$temp['_rev'] = $this->rev;
				$json         = json_encode($temp);
				$result       = $dbh->put($json, $this->id);
			}
		}
		
		$this->rev = $result['rev'];
	}
	
	public function delete($id = null)
	{
		if(!$this->isNew && $id != null)
		{
			$dbh       =& Database::connection();
			$files     = array();
			
			foreach ($this->columns as $key=>$column)
			{	
				if ($column instanceof File)
					$files[$key] = $column;
			}
			
			if (count($files) > 0)
			{
				foreach ($files as $key=>$value)
				{
					if($value->value)
					{
						$path = $value->path;

						if($value->shouldAppendColumnToPath)
							$path .= '/'.$value->column;

						FileUtils::delete($path.'/'.$value->value);
					}
				}
			}
			
			$dbh->delete($this->id, $this->rev);
		}
	}
}
?>